package com.wrupple.muba.common.shared.services.impl;

import java.util.HashMap;

import com.google.gwt.http.client.URL;
import com.google.gwt.user.client.History;
import com.wrupple.muba.common.shared.services.UrlParser;

public class UrlParserImpl implements UrlParser {
	private static class SplitHistoryToken {
		String itemId;
		String parameters;
	}
	@Override
	public HashMap<String, String> getParametersFromUrl(String token) {
		String qs = splitTokenAndQuery(token).parameters;
		HashMap<String, String> paramMap = new HashMap<String, String>();
		if (qs != null && qs.length() > 1) {
			for (String kvPair : qs.split("&")) {
				String[] kv = kvPair.split("=", 2);
				if (kv.length > 1) {
					paramMap.put(kv[0], URL.decodeQueryString(kv[1]));
				}

			}
		}
		return paramMap;
	}

	

	private SplitHistoryToken splitTokenAndQuery(String url) {
		String historyToken = url == null ? History.getToken() : url;
		SplitHistoryToken regreso = new SplitHistoryToken();
		String token = null;
		String queryString = null;
		if (historyToken == null) {
			token = "";
			queryString = null;
		} else {
			int index = historyToken.indexOf('?');
			if (index != -1) {
				token = historyToken.substring(0, index);
				if ((index + 1) < (historyToken.length() - 1)) {
					queryString = historyToken.substring((index + 1), historyToken.length());
				} else {
					queryString = null;
				}
			} else {
				token = historyToken;
				queryString = null;
			}
		}
		regreso.itemId = token;
		regreso.parameters = queryString;
		return regreso;
	}
}
